/*
 * The MIT License
 *
 * Copyright (c) 2013-2016 reark project contributors
 *
 * https://github.com/reark/reark/graphs/contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package io.reark.rxgithubapp.advanced.ability;

import com.bumptech.glide.Glide;
import io.reark.reark.utils.Log;
import io.reark.rxgithubapp.ResourceTable;
import io.reark.rxgithubapp.advanced.data.DbUtils;
import io.reark.rxgithubapp.advanced.data.GithubDb;
import io.reark.rxgithubapp.advanced.data.UserSettings;
import io.reark.rxgithubapp.advanced.widget.WidgetProvider;
import io.reark.rxgithubapp.advanced.widget.WidgetService;
import io.reark.rxgithubapp.shared.network.NetworkApi;
import io.reark.rxgithubapp.shared.pojo.GitHubRepository;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.ComponentProvider;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import java.io.IOException;

/**
 * MainAbility.
 *
 * @since 2021-08-06
 */
public class MainAbility extends Ability {
    private static final String TAG = MainAbility.class.getSimpleName();
    private static final int INVALID_FORM_ID = -1;
    private Intent intentService;
    private final DatabaseHelper helper = new DatabaseHelper(this);
    private ProviderFormInfo formInfo;
    private OrmContext connect;
    private static final int DEFAULT_REPOSITORY_ID = 15491874;
    Button button;
    private Text titleTextView;
    private Text stargazersTextView;
    private Text forksTextView;
    private Image avatarImageView;
    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_repository);
        Log.d(TAG, "onCreateForm");
        intentService = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(WidgetService.class.getName())
                .build();
        intentService.setOperation(operation);
        startAbility(intentService);
        titleTextView = (Text) findComponentById(ResourceTable.Id_widget_layout_title);
        stargazersTextView = (Text) findComponentById(ResourceTable.Id_widget_layout_stargazers);
        forksTextView = (Text) findComponentById(ResourceTable.Id_widget_layout_forks);
        avatarImageView = (Image) findComponentById(ResourceTable.Id_widget_avatar_image_view_1);
        button = (Button) findComponentById(ResourceTable.Id_repository_fragment_choose_repository_button);
        button.setClickedListener(component -> {
            Intent intent1=new Intent();
            System.out.println("---------setClickedListener---------");
            Operation operation1 = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName(getBundleName())
                    .withAbilityName(ChooseRepositoryAbility.class.getName())
                    .build();
            intent1.setOperation(operation1);
            startAbility(intent1);

        });

        }


    @Override
    protected void onActive() {
        super.onActive();
        UserSettings userSettings = DbUtils.getWidget(this);
        if (!userSettings.getName().equals("")) {
            titleTextView.setText(userSettings.getName());
            stargazersTextView.setText("stars: " + userSettings.getStargazersCount());
            forksTextView.setText("forks: " + userSettings.getForksCount());
            Glide.with(getContext())
                    .load(userSettings.getAvatarUrl())
                    .fitCenter()
                    .skipMemoryCache(true)
                    .into(avatarImageView);
            return;
        }
        String baseUrl = "";
        try {
            baseUrl =  getResourceManager().getElement(io.reark.rxgithubapp.shared.ResourceTable.String_base_url).getString();
        } catch (IOException | NotExistException | WrongTypeException e) {
            Log.d(TAG,e.getMessage());
        }
        Call<GitHubRepository> s =new NetworkApi(baseUrl).getRepository(DEFAULT_REPOSITORY_ID);
        s.enqueue(new Callback<GitHubRepository>() {
            @Override
            public void onResponse(Call<GitHubRepository> call, Response<GitHubRepository> response) {
                GitHubRepository repository = response.body();

                titleTextView.setText(repository.getName());
                stargazersTextView.setText("stars: " + repository.getStargazersCount());
                forksTextView.setText("forks: " + repository.getForksCount());
                Glide.with(getContext())
                        .load(repository.getOwner().getAvatarUrl())
                        .fitCenter()
                        .skipMemoryCache(true)
                        .into(avatarImageView);

                UserSettings userSettings = new UserSettings();
                userSettings.setId((long) repository.getId());
                userSettings.setName(repository.getName());
                userSettings.setStargazersCount(repository.getStargazersCount());
                userSettings.setForksCount(repository.getForksCount());
                userSettings.setAvatarUrl(repository.getOwner().getAvatarUrl());
                DbUtils.setWidget(userSettings, getContext());
            }

            @Override
            public void onFailure(Call<GitHubRepository> call, Throwable throwable) {

            }
        });
    }
    @Override
    protected ProviderFormInfo onCreateForm(Intent intent) {
        long formId;
        if (intent == null) {
            return new ProviderFormInfo();
        }
        Log.d(TAG, "onCreateForm");

        int layoutId = ResourceTable.Layout_widget_layout;

        if (intent.hasParameter(AbilitySlice.PARAM_FORM_IDENTITY_KEY)) {
            formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        } else {
            return new ProviderFormInfo();
        }
        formInfo = new ProviderFormInfo(layoutId, this);
        UserSettings userSettings = DbUtils.getWidget(this);
        userSettings.setId(formId);
        ComponentProvider componentProvider = WidgetProvider.getComponentProvider(this);
        formInfo.mergeActions(componentProvider);
        if (connect == null) {
            connect = helper.getOrmContext(DbUtils.A_LIAS, DbUtils.DB, GithubDb.class);
        }
        try {
            DbUtils.insert(userSettings, connect);
        } catch (Exception e) {
            DbUtils.delete(userSettings.getId(), connect);
        }
        return formInfo;
    }

    @Override
    protected void onDeleteForm(long formId) {
        super.onDeleteForm(formId);
        DbUtils.delete(formId, connect);
        Log.d(TAG, "onDeleteForm");
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
